package com.guguskins.back.controller;


import com.guguskins.back.common.annotation.Authorized;
import com.guguskins.back.entity.GuMarket;
import com.guguskins.back.entity.vo.MarketVo;
import com.guguskins.back.entity.vo.PageVo;
import com.guguskins.back.entity.vo.ResultVo;
import com.guguskins.back.service.GuMarketService;
import com.guguskins.back.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-07-02
 */
@RestController
@RequestMapping("/market")
public class GuMarketController {

    @Autowired
    private GuMarketService marketService;

    @GetMapping("/page")
    public ResultVo getPage(@RequestParam(value = "p", required = false, defaultValue = "1") int p,
                            @RequestParam(value = "size", required = false, defaultValue = "10") int size,
                            @RequestParam(value = "type", required = false, defaultValue = "-1") int type) {
        PageVo<MarketVo> marketPageVo = marketService.getPage(p, size, type);
        return ResultVo.success(marketPageVo);
    }

    @PostMapping("/exchange")
    @Authorized
    public ResultVo exchange(@RequestHeader("token") String token,
                             @RequestBody GuMarket market) {
        Long userId = JwtUtil.verifyToken(token).get("userId", Long.class);
        return ResultVo.success(marketService.exchange(userId, market.getMarketId()), "兑换成功");
    }

    @GetMapping("/back/page")
    public ResultVo backPage(@RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
                             @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize) {
        return ResultVo.success(marketService.backPage(pageNum, pageSize));
    }
    @PostMapping("back/insert")
    public ResultVo insert(@RequestBody @Validated GuMarket market){
        if(market.getMarketItemId()==null){
            return ResultVo.fail("奖品不能为空");

        }
        if(market.getMarketPrice()==null){
            return ResultVo.success("价钱不能小于1.00");
        }
      marketService.save(market);
      return ResultVo.success("添加成功");
    }
    @PostMapping("back/update")

    public ResultVo backUpdate(@RequestBody @Validated GuMarket market ){
        if(Integer.parseInt(market.getMarketPrice().toString())<1){

            return ResultVo.success("价钱不能小于1.00");
        }

        boolean b = marketService.updateById(market);

        return ResultVo.success("修改成功");
    }
    @GetMapping("back/findById")
    public ResultVo findById(@RequestParam(value = "marketId",required = false)Integer marketId)
    {

      return ResultVo.success ( marketService.getById(marketId),"查找成功");
    }

}
